<template>
  <Dialog v-model="dialogVisible" :title="title">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="题库名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入题库名称" />
      </el-form-item>
      <el-form-item label="验证维度" prop="dimension">
        <el-input v-model="formData.dimension" placeholder="请输入验证维度" />
      </el-form-item>
      <el-form-item label="启动" prop="enable">
        <el-switch v-model="formData.enable" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as CatStoreApi from '@/api/pm/catstore'

defineOptions({ name: 'PmCatStoreForm' })

const message = useMessage()

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const mode = ref<'create' | 'update'>('create')
const title = computed(() => (mode.value === 'create' ? '新增题库' : '编辑题库'))

const formData = ref<any>({
  id: undefined,
  name: undefined,
  remark: undefined,
  dimension: undefined,
  enable: 1,
  createBy: undefined,
  createTime: undefined,
  questionCount: undefined,
  terminationThreshold: undefined
})

const formRules = reactive({
  name: [{ required: true, message: '请输入题库名称', trigger: 'blur' }],
  dimension: [{ required: true, message: '请输入验证维度', trigger: 'blur' }]
})

const open = async (openMode: 'create' | 'update', id?: number) => {
  mode.value = openMode
  dialogVisible.value = true
  resetForm()
  if (openMode === 'update' && id) {
    formLoading.value = true
    try {
      const data = await CatStoreApi.getCatStoreDetail(id)
      formData.value = { ...data }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  const valid = await formRef.value?.validate()?.catch(() => false)
  if (!valid) return
  formLoading.value = true
  try {
    if (mode.value === 'update') {
      await CatStoreApi.updateCatStore(formData.value)
      message.success('修改成功')
    } else {
      // 等待提供新增接口
      message.success('新增成')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    remark: undefined,
    dimension: undefined,
    enable: 1,
    createBy: undefined,
    createTime: undefined,
    questionCount: undefined,
    terminationThreshold: undefined
  }
  formRef.value?.resetFields?.()
}

</script>
